package com.rao.travel.controller;

import com.rao.travel.pojo.Role;
import com.rao.travel.pojo.UserInfo;
import com.rao.travel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author Srao
 * @version 1.0
 * @className UserController
 * @date 2019/10/31 20:27
 * @package com.rao.travel.controller
 * @description
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*查询所有用户*/
    @RequestMapping("/findAll.do")
    @PreAuthorize("hasRole('ROLE_ADMIN')")//只有具有管理员权限的用户才能查看所有用户
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        List<UserInfo> userList = userService.findAll();
        modelAndView.addObject("userList", userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    /*保存一个用户*/
    @RequestMapping("/save.do")
    public String save(UserInfo userInfo){
        userService.save(userInfo);
        return "redirect:findAll.do";
    }

    /*根据用户id查询用户*/
    @RequestMapping("findById.do")
    @PreAuthorize("authentication.principal.username == 'admin'")//只有叫做admin的用户才能添加角色，就算有管理员权限也不能添加
    public ModelAndView findById(String id){
        ModelAndView modelAndView = new ModelAndView();
        UserInfo user = userService.findById(id);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("user-show");
        return modelAndView;
    }

    /*跳转到为用户添加角色页面*/
    @RequestMapping("findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id")String id){
        ModelAndView modelAndView = new ModelAndView();
        UserInfo userInfo = userService.findById(id);
        List<Role> roleList = userService.findOtherRole(userInfo);
        modelAndView.addObject("user", userInfo);
        modelAndView.addObject("roleList", roleList);
        modelAndView.setViewName("user-role-add");
        return modelAndView;
    }

    /*为用户添加角色*/
    @RequestMapping("addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId")String userId,
                                @RequestParam(name = "ids")String[] ids){

        userService.addRoleToUser(userId, ids);
        return "redirect:findAll.do";
    }
}
